/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.yami.shop.bean.app.dto.DeliveryDto;
import com.yami.shop.bean.bo.OrderChangeShopWalletAmountBO;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.enums.*;
import com.yami.shop.bean.event.*;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.OrderRefundParam;
import com.yami.shop.bean.param.UserManagerParam;
import com.yami.shop.bean.pay.RefundInfoDto;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.dao.OrderRefundMapper;
import com.yami.shop.dao.ProdExtensionMapper;
import com.yami.shop.dao.SkuStockMapper;
import com.yami.shop.service.*;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yami
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderRefundServiceImpl extends ServiceImpl<OrderRefundMapper, OrderRefund> implements OrderRefundService {

    @Value("${yami.expose.operation.auth:}")
    private Boolean permission;

    private final OrderRefundMapper orderRefundMapper;
    private final OrderService orderService;
    private final NotifyTemplateService notifyTemplateService;
    private final ShopWalletService shopWalletService;
    private final SkuService skuService;
    private final ProdExtensionMapper prodExtensionMapper;
    private final SkuStockMapper skuStockMapper;
    private final OrderItemService orderItemService;
    private final RefundOrderSettlementService refundOrderSettlementService;
    private final RefundDeliveryService refundDeliveryService;
    private final OrderSettlementService orderSettlementService;
    private final StockBillLogService stockBillLogService;
    private final RefundAddrService refundAddrService;
    private final ApplicationContext applicationContext;
    private final DeliveryService deliveryService;
    private final OrderInvoiceService orderInvoiceService;
    private final ApplicationEventPublisher eventPublisher;
    private final RefundInfoService refundInfoService;
    private final PayInfoService payInfoService;


    /**
     * 获取分页对象
     */
    @Override
    public IPage<OrderRefundDto> getPage(Page page, OrderRefundDto orderRefundDto, String startTime, String endTime, Integer type) {
        IPage<OrderRefundDto> orderRefundDtoIpage = orderRefundMapper.getPage(page, orderRefundDto, startTime, endTime);
        List<OrderRefundDto> records = orderRefundDtoIpage.getRecords();
        for (OrderRefundDto record : records) {
            getReasonType(record);
            getRefundTypeByOrderItem(record, type);
            if (BooleanUtil.isFalse(permission) && Objects.nonNull(record.getBuyerMobile())) {
                record.setBuyerMobile(PhoneUtil.hideBetween(record.getBuyerMobile()).toString());
            }
        }
        return orderRefundDtoIpage;
    }

    /**
     * 对退款原因进行国际化
     *
     * @param record
     */
    private void getReasonType(OrderRefundDto record) {
        try {
            BuyerReasonType reasonType = BuyerReasonType.instance(Integer.valueOf(record.getBuyerReason()));
            if (Objects.nonNull(reasonType)) {
                record.setBuyerReason(I18nMessage.getDbLang() == 0 ? reasonType.getCn() : reasonType.getEn());
                if (reasonType.value().equals(BuyerReasonType.GROUP_FAILED.value())) {
                    // 当退款原因为拼团失败时，退款说明与卖家备注进行国际化
                    record.setBuyerDesc(I18nMessage.getDbLang() == 0 ? reasonType.getCn() : reasonType.getEn());
                    record.setSellerMsg(I18nMessage.getDbLang() == 0 ? reasonType.getCn() : reasonType.getEn());
                }
            }
        } catch (NumberFormatException ignored) {
            //如果出现BuyerReasonType没有的类型，则默认即可
        }
    }

    /**
     * 根据编码查询退款单信息
     *
     * @param refundSn 退款单编码
     * @return 退款包装对象
     */
    @Override
    public OrderRefundDto getOrderRefundByRefundSn(String refundSn) {
        OrderRefundDto orderRefundDto = orderRefundMapper.getOrderRefundByRefundSn(refundSn);
        if (orderRefundDto == null) {
            return null;
        }
        // 如果是单项退款,且订单状态为待发货，则退款数量为：主商品数量+赠品数量
        if (orderRefundDto.getRefundType().equals(RefundType.SINGLE.value()) && orderRefundDto.getStatus().equals(OrderStatus.PADYED.value())) {
            Integer prodNum = orderItemService.getOrderItemProdNum(orderRefundDto.getOrderItemId());
            orderRefundDto.setGoodsNum(prodNum);
        }
        //获取总数，如果为0则为全部
        if (orderRefundDto.getGoodsNum() == 0) {
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderRefundDto.getOrderNumber()));
            orderRefundDto.setGoodsNum(order.getProductNums());
        }
        // 判断退款单类型（1:整单退款,2:单个物品退款）
        getRefundTypeByOrderItem(orderRefundDto, 1);
        orderRefundDto.setIsCancel(true);
        // 如果是单项退款,且订单状态为待发货，则判断退款操作是否可以取消
        if (orderRefundDto.getRefundType().equals(RefundType.SINGLE.value()) && orderRefundDto.getStatus().equals(OrderStatus.PADYED.value())) {
            Integer orderRefundNums = orderRefundMapper.getOrderRefundCountByRefundSn(orderRefundDto.getRefundSn());
            Integer orderItemNums = orderItemService.count(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderRefundDto.getOrderNumber()));
            //订单退款项等于订单项(多个订单项) -> 该订单已全部进行退款申请 -> 不能进行取消退款操作
            if (orderItemNums > 1 && orderRefundNums.equals(orderItemNums)) {
                orderRefundDto.setIsCancel(false);
            }
        }
        return orderRefundDto;
    }

    /**
     * 根据退款ID获取退款单信息
     *
     * @param refundId 退款单ID
     * @return
     */
    @Override
    public OrderRefundDto getOrderRefundById(Long refundId, Long shopId) {
        OrderRefundDto orderRefundDto = orderRefundMapper.getById(refundId, shopId);
        if (orderRefundDto == null) {
            // 无法获取退款订单信息
            throw new YamiShopBindException("yami.unable.refund.information");
        }
        // 判断退款单类型（1:整单退款,2:单个物品退款）
        getRefundTypeByOrderItem(orderRefundDto, RefundType.ALL.value());
        getReasonType(orderRefundDto);
        if (Objects.equals(orderRefundDto.getApplyType(), RefundApplyType.RETURN_REFUND.value())) {
            orderRefundDto.setDeliveryDto(getDeliverInfoByRefundSn(orderRefundDto.getRefundSn()));
        }
        return orderRefundDto;
    }

    @Override
    public DeliveryDto getDeliverInfoByRefundSn(String refundSn) {
        RefundDelivery refundDelivery = refundDeliveryService.getOne(new LambdaQueryWrapper<RefundDelivery>()
                .eq(RefundDelivery::getRefundSn, refundSn));
        DeliveryDto deliveryDto = null;
        if (Objects.nonNull(refundDelivery) && Objects.nonNull(refundDelivery.getDeyId())) {
            try {
                deliveryDto = deliveryService.query(refundDelivery.getDeyId(), refundDelivery.getDeyNu(), refundDelivery.getReceiverMobile());
                if(Objects.nonNull(deliveryDto)){
                    deliveryDto.setCompanyName(refundDelivery.getDeyName());
                    deliveryDto.setDvyFlowId(refundDelivery.getDeyNu());
                }
            } catch (Exception e) {
                log.error("物流查询错误：", e);
                // 查询出错
                throw new YamiShopBindException("yami.query.error");
            }
        }
        return deliveryDto;
    }

    /**
     * 生成退款单
     *
     * @param orderRefund 退款对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyRefund(OrderRefund orderRefund) {
        // 生成退款单
        save(orderRefund);
        // 更新订单状态
        Order order = orderService.getById(orderRefund.getOrderId());
        order.setRefundStatus(RefundStatusEnum.APPLY.value());
        orderService.updateById(order);

        // 消息推送-申请退款
        notifyTemplateService.sendNotifyOfApplyRefund(order, orderRefund);
    }


    /**
     * 判断退款单类型（1:整单退款,2:单个物品退款）
     * sysType,1.展示赠品信息，0.不展示
     */
    private void getRefundTypeByOrderItem(OrderRefundDto orderRefundDto, Integer sysType) {
        if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
            List<OrderItem> items = orderItemService.getUnGiveawayOrderItemsByOrderNumber(orderRefundDto.getOrderNumber(), I18nMessage.getDbLang());
            orderRefundDto.setRefundScore(items.stream().mapToLong(OrderItem::getUseScore).sum());
            //放入赠品信息
            if (Objects.equals(sysType, 1)) {
                List<Long> itemIds = items.stream().map(OrderItem::getOrderItemId).collect(Collectors.toList());

                List<OrderItem> giveawayItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getGiveawayOrderItemId, itemIds));
                Map<Long, List<OrderItem>> giveawayItemMap = giveawayItems.stream().collect(Collectors.groupingBy(OrderItem::getGiveawayOrderItemId));
                for (OrderItem orderItem : items) {
                    // 放入赠品
                    if (giveawayItemMap.containsKey(orderItem.getOrderItemId())) {
                        orderItem.setGiveawayList(giveawayItemMap.get(orderItem.getOrderItemId()));
                    }
                }
            }
            orderRefundDto.setOrderItems(items);
        } else {
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderId, orderRefundDto.getOrderId()).eq(Order::getShopId, orderRefundDto.getShopId()));
            orderRefundDto.setFreightAmount(order.getFreightAmount());
            OrderItem item = orderItemService.getByOrderItemId(orderRefundDto.getOrderItemId(), I18nMessage.getDbLang());
            orderRefundDto.getOrderItems().add(item);
            orderRefundDto.setRefundScore(item.getUseScore());
            //放入赠品信息
            String returnGiveawayIds = orderRefundDto.getReturnGiveawayIds();
            if (StrUtil.isBlank(returnGiveawayIds) || Objects.equals(sysType, 0)) {
                return;
            }
            List<String> itemIds = Arrays.asList(returnGiveawayIds.split(StrUtil.COMMA));
            List<OrderItem> giveawayItems = orderItemService.list(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderItemId, itemIds));
            item.setGiveawayList(giveawayItems);
        }
    }

    /**
     * 卖家处理（退款/返回退货地址）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderRefundDto processRefundOrder(OrderRefundParam orderRefundParam, Long shopId) {
        OrderRefundDto orderRefundDto = getOrderRefundById(orderRefundParam.getRefundId(), shopId);
        if (Objects.equals(-1, orderRefundDto.getReturnMoneySts())) {
            // 买家已取消申请
            throw new YamiShopBindException("yami.order.refund.cancel");
        }
        Date now = new Date();


        // 是否同意退款
        if (Objects.equals(orderRefundParam.getRefundSts(), RefundStsType.DISAGREE.value())) {
            // 不同意退款
            disagreeRefund(orderRefundParam, orderRefundDto);
        } else {
            // 正在处理退款的状态
            orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.PROCESSING.value());

            // 判断是退款退货/仅退款(1:仅退款 2:退款退货)
            if (Objects.equals(orderRefundDto.getApplyType(), 1)) {
                // 同意退款
                checkLastRefund(orderRefundDto);
                agreeRefund(orderRefundDto);
                // 减少商家结算金额
                subShopSettlementAmount(orderRefundDto);
            } else {
                // 同意退款退货操作
                // 设置退货物流信息
                RefundAddr refundAddr = refundAddrService.getById(orderRefundParam.getRefundAddrId());
                if (refundAddr == null) {
                    // 请设置退货物流信息
                    throw new YamiShopBindException("yami.set.refund.information");
                }
                RefundDelivery refundDelivery = new RefundDelivery();
                refundDelivery.setShopId(orderRefundDto.getShopId());
                refundDelivery.setRefundSn(orderRefundDto.getRefundSn());
                refundDelivery.setUserId(orderRefundDto.getUserId());
                refundDelivery.setReceiverName(refundAddr.getReceiverName());
                refundDelivery.setReceiverMobile(refundAddr.getReceiverMobile());
                refundDelivery.setReceiverTelephone(refundAddr.getReceiverTelephone());
                refundDelivery.setReceiverPostCode(refundAddr.getPostCode());
                String addr = refundAddr.getProvince() + refundAddr.getCity() + refundAddr.getArea() + refundAddr.getAddr();
                refundDelivery.setReceiverAddr(addr);
                refundDelivery.setCreateTime(new Date());
                refundDeliveryService.save(refundDelivery);

                // 消息推送-同意退款
                notifyTemplateService.sendNotifyByRefund(orderRefundDto, SendType.AGREE_REFUND);
            }

        }

        // 设置卖家备注
        orderRefundDto.setSellerMsg(orderRefundParam.getSellerMsg());
        // 受理时间
        orderRefundDto.setHandelTime(now);
        // 更新时间
        orderRefundDto.setUpdateTime(now);
        orderRefundDto.setBuyerReason(null);
        // 更新数据
        updateById(orderRefundDto);
        return orderRefundDto;
    }

    /**
     * 收到货同意退款
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderRefundDto returnMoney(OrderRefundParam orderRefundParam, Long shopId) {
        // 获取退款单信息
        OrderRefundDto orderRefundDto = getOrderRefundById(orderRefundParam.getRefundId(), shopId);

        if (!Objects.equals(ReturnMoneyStsType.CONSIGNMENT.value(), orderRefundDto.getReturnMoneySts())) {
            // 订单状态已经发生改变，请勿重复操作
            throw new YamiShopBindException("yami.order.status.change");
        }
        if (Objects.equals(-1, orderRefundDto.getReturnMoneySts())) {
            // 买家已取消申请
            throw new YamiShopBindException("yami.order.refund.cancel");
        }
        Date now = new Date();

        // 是否同意退款
        if (Objects.equals(orderRefundParam.getRefundSts(), RefundStsType.AGREE.value())) {
            // 减少商家结算金额
            subShopSettlementAmount(orderRefundDto);

            // 同意操作
            orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.RECEIVE.value());
            // 同意退款
            agreeRefund(orderRefundDto);

        } else {
            disagreeRefund(orderRefundParam, orderRefundDto);
        }

        // 是否收到货
        orderRefundDto.setIsReceiver(orderRefundParam.getIsReceiver());

        // 收货时间(收到商品才更新)
        if (orderRefundDto.getIsReceiver()) {
            orderRefundDto.setReceiveTime(now);
        }

        // 更新时间
        orderRefundDto.setUpdateTime(now);
        orderRefundDto.setBuyerReason(null);
        // 更新数据
        updateById(orderRefundDto);

        return orderRefundDto;
    }

    /**
     * 减少商家结算金额/未结算金额
     */
    private void subShopSettlementAmount(OrderRefundDto orderRefundDto) {
        Long shopId = orderRefundDto.getShopId();
        // 同意退款，判断商家是否还有金额进行退款
        Order order = orderService.getOrderByOrderNumber(orderRefundDto.getOrderNumber());
        if (order == null) {
            // 未找到该订单信息
            throw new YamiShopBindException("yami.no.found.order");
        }

        // 实付金额
        double actualTotal;
        double platformCommission;
        double changePlatformCommission;
        Double rate = 0.0;
        double distributionAmount;
        double shopAmount;
        if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
            actualTotal = order.getActualTotal();
            platformCommission = order.getPlatformCommission();
            distributionAmount = order.getDistributionAmount();
            shopAmount = Arith.sub(order.getReduceAmount(),order.getPlatformAmount());
        } else {
            OrderItem item = orderItemService.getByOrderItemId(orderRefundDto.getOrderItemId(), I18nMessage.getDbLang());
            actualTotal = item.getActualTotal();
            // 平台佣金
            platformCommission = item.getPlatformCommission();
            rate = item.getRate();
            // 分销金额 = 直推分销金额 + 间推分销金额
            distributionAmount = item.getDistributionAmount() + item.getDistributionParentAmount();
            shopAmount = Arith.sub(item.getShareReduce(),item.getPlatformShareReduce());
        }


        OrderChangeShopWalletAmountBO orderChangeShopWalletAmountBO = new OrderChangeShopWalletAmountBO();
        orderChangeShopWalletAmountBO.setOrderStatus(order.getStatus());
        orderChangeShopWalletAmountBO.setActualTotal(actualTotal);
        orderChangeShopWalletAmountBO.setRefundAmount(orderRefundDto.getRefundAmount());
        orderChangeShopWalletAmountBO.setPlatformAllowanceAmount(orderRefundDto.getPlatformRefundAmount());
        orderChangeShopWalletAmountBO.setOrderNumber(order.getOrderNumber());
        orderChangeShopWalletAmountBO.setRefundSn(orderRefundDto.getRefundSn());
        orderChangeShopWalletAmountBO.setShopId(orderRefundDto.getShopId());
        orderChangeShopWalletAmountBO.setOrderItemId(orderRefundDto.getOrderItemId());
        orderChangeShopWalletAmountBO.setPlatformCommission(platformCommission);
        orderChangeShopWalletAmountBO.setChangePlatformCommission(orderRefundDto.getPlatformRefundCommission());
        orderChangeShopWalletAmountBO.setShopReduceAmount(shopAmount);
        orderChangeShopWalletAmountBO.setRate(rate);
        orderChangeShopWalletAmountBO.setDistributionAmount(distributionAmount);
        shopWalletService.refundShopAmountByRefund(orderChangeShopWalletAmountBO);
//        double shopRealRefundAmount = orderRefundDto.getRefundAmount();
//
//        // 订单发起退款时，扣除商家金额应该加上平台部分
//        // 如果订单100元，平台出10元给商家（如平台10元优惠券，会员折扣9折），用户支付90元，此时商家结算时，要拿到100元，。
//        // 当用户进行退款，有一部分钱是平台出的，平台出的这部分钱，要将平台出的这部分钱按数据库存的平台优惠金额从商家那里扣除，如用户退90块，商家结算减少100块。
//        if (Objects.nonNull(order.getPlatformAmount()) && order.getPlatformAmount() > 0) {
//            if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
//                shopRealRefundAmount = Arith.add(shopRealRefundAmount, order.getPlatformAmount());
//            } else {
//                OrderItem item = orderItemService.getById(orderRefundDto.getOrderItemId());
//                shopRealRefundAmount = Arith.add(shopRealRefundAmount, item.getPlatformShareReduce());
//            }
//        }
//
//
//        // 店铺真正退款的金额是不用退分销员的那部分的
//        // 如果订单100元，分销10元，10元的分销费用由商家出，此时商家结算时，拿到90元。
//        // 当用户进行退款，退1块的时候，分销会无效，此时商家拿回给出去的10元分销费用，并将1元给到退款用户，此时商家因为退款赚9元。 shopRealRefundAmount = -9
//        // 当用户进行退款，退11块的时候，分销会无效，此时商家拿回给出去的10元分销费用，并将11元给到退款用户，此时商家因为退款亏1元。shopRealRefundAmount = 1
//        if (orderRefundDto.getDistributionTotalAmount() != null) {
//            shopRealRefundAmount = Arith.sub(shopRealRefundAmount, orderRefundDto.getDistributionTotalAmount());
//        }
//
//        ShopWallet shopWallet = shopWalletMapper.selectOne(new LambdaQueryWrapper<ShopWallet>().eq(ShopWallet::getShopId, shopId));
//        ShopWallet newShopWallet = mapperFacade.map(shopWallet, ShopWallet.class);
//
//        // 已确认收货的订单扣除已结算的金额
//        if (Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value())) {
//            // 平台把退款金额归还商家，商家退还金额到用户
//            if (shopWallet.getSettledAmount() < shopRealRefundAmount) {
//                // 您的可提现金额不足，无法进行退款
//                throw new YamiShopBindException("yami.availabl.cash.refund");
//            }
//            newShopWallet.setSettledAmount(Arith.sub(shopWallet.getSettledAmount(), shopRealRefundAmount));
//            newShopWallet.setTotalSettledAmount(Arith.sub(shopWallet.getTotalSettledAmount(), shopRealRefundAmount));
//        }
//        // 1. 订单未确认收货则扣未结算金额
//        // 2. 商家撤销拼团活动时失效拼团时，将待成团的队伍进行退款
//        if (Objects.equals(order.getStatus(), OrderStatus.PADYED.value()) || Objects.equals(order.getStatus(), OrderStatus.CONSIGNMENT.value()) || Objects.equals(order.getStatus(), OrderStatus.WAIT_GROUP.value())) {
//
//            if (shopWallet.getUnsettledAmount() < shopRealRefundAmount) {
//                // 您的待结算金额不足，无法进行退款
//                throw new YamiShopBindException("yami.not.sufficient.refund");
//            }
//            newShopWallet.setUnsettledAmount(Arith.sub(shopWallet.getUnsettledAmount(), shopRealRefundAmount));
//        }
//        newShopWallet.setUpdateTime(new Date());
//        // 添加钱包日志记录
//        shopWalletLogService.saveShopWalletLog(shopWallet, newShopWallet, ShopWalletChangeReason.ORDER_REFUND, orderRefundDto.getOrderNumber());
//
//        // 更新商家钱包信息
//        if (shopWalletMapper.updateById(newShopWallet) != 1) {
//            // 更新店铺钱包信息失败
//            throw new YamiShopBindException("yami.cannot.update.wallet");
//        }
    }

    /**
     * 不同意退款
     */
    private void disagreeRefund(OrderRefundParam orderRefundParam, OrderRefundDto orderRefundDto) {
        // 不同意退款
        orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.FAIL.value());
        // 拒绝原因
        orderRefundDto.setRejectMessage(orderRefundParam.getRejectMessage());
        orderRefundDto.setRejectTime(new Date());

        // 更新订单
        Order order = orderService.getById(orderRefundDto.getOrderId());
        Integer orderRefundSuccessCount = orderRefundMapper.selectCount(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getOrderId, orderRefundDto.getOrderId())
                .eq(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.SUCCESS.value()));
        // 如果有订单项退款成功，则订单状态为部分退款成功，否则为退款失败
        if (orderRefundSuccessCount > 0) {
            order.setRefundStatus(RefundStatusEnum.PARTIAL_SUCCESS.value());
        } else {
            order.setRefundStatus(RefundStatusEnum.DISAGREE.value());
        }
        orderService.updateById(order);

        // 消息推送--拒绝退款
        notifyTemplateService.sendNotifyByRefund(orderRefundDto, SendType.REFUSE_REFUND);
    }

    /**
     * 买家提交物流信息
     * @param orderRefund    退款单对象
     * @param refundDelivery 退款物流单对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitExpress(OrderRefund orderRefund, RefundDelivery refundDelivery) {
        refundDeliveryService.updateById(refundDelivery);
        updateById(orderRefund);

        // 消息推送-用户已退货
        Order order = orderService.getById(orderRefund.getOrderId());
        order.setRemarks(refundDelivery.getSenderRemarks());
        notifyTemplateService.sendNotifyByUserRefundDelivery(order, SendType.RETURN_REFUND);
    }

    /**
     * 系统自动退款操作（批量）
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void systemAutoRefundBatch(List<OrderRefundDto> orderRefundDtoList) {
        for (OrderRefundDto orderRefundDto : orderRefundDtoList) {
            agreeRefund(orderRefundDto);
            update(orderRefundDto, new LambdaQueryWrapper<OrderRefund>()
                    .eq(OrderRefund::getRefundSn, orderRefundDto.getRefundSn()));
            // 减少商家未结算金额
            subShopSettlementAmount(orderRefundDto);

            try {
                submitWxRefund(orderRefundDto);
            } catch (YamiShopBindException e) {
                WxPayException wxPayException = (WxPayException) e.getObject();
                if (Objects.equals("订单已全额退款", wxPayException.getErrCodeDes())) {
                    continue;
                }
                throw e;
            }
        }
    }

    /**
     * 系统验证退款结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void verifyRefund(RefundInfo refundInfo, String payRefundId) {
        // 查询退款结算记录
        RefundOrderSettlement refundOrderSettlement = refundOrderSettlementService.getOne(
                new LambdaQueryWrapper<RefundOrderSettlement>().eq(RefundOrderSettlement::getRefundSn, refundInfo.getRefundId()));

        // 判断退款结算记录是否为申请状态
        if (refundOrderSettlement == null || refundOrderSettlement.getRefundStatus() != 1) {
            // 退款已处理，无需重复处理
            throw new YamiShopBindException("yami.refund.processed");
        }

        // 更新退款结算记录
        refundOrderSettlement.setPayRefundId(payRefundId);
        refundOrderSettlement.setRefundStatus(2);
        if (!refundOrderSettlementService.updateById(refundOrderSettlement)) {
            // 服务器繁忙，请稍后再试
            throw new YamiShopBindException("yami.network.busy");
        }
        // 更新订单
        Order order = orderService.getOrderByOrderNumber(refundInfo.getOrderNumber());
        int oldOrderStatus = order.getStatus();

        OrderRefundDto orderRefundDto = getOrderRefundByRefundSn(refundInfo.getRefundId());
        // 退款成功（保存退款结算记录、更新订单、还原库存）
        refundSuccess(order, orderRefundDto);

        // 推送退款成功事件
        applicationContext.publishEvent(new OrderRefundSuccessEvent(orderRefundDto));
        if (Objects.equals(oldOrderStatus, OrderStatus.SUCCESS.value()) && Objects.equals(order.getStatus(), OrderStatus.CLOSE.value())) {
            // 还原成长值
            applicationContext.publishEvent(new RefundGrowthEvent(order.getOrderNumber()));
        }

        // 可以退款的状态 && 现在订单关闭了 && 因为退款导致订单关闭
        // 如果订单因为退款关闭，要进行结算给商家的操作，这个结算的计算是退款完成后结算的，所以不要随便改变顺序
        boolean canRefundFlag = Objects.equals(oldOrderStatus, OrderStatus.PADYED.value())
                || Objects.equals(oldOrderStatus, OrderStatus.CONSIGNMENT.value())
                || Objects.equals(oldOrderStatus, OrderStatus.SUCCESS.value());
        if (canRefundFlag && Objects.equals(order.getStatus(), OrderStatus.CLOSE.value())
                && Objects.equals(order.getCloseType(), OrderCloseType.REFUND.value())) {
            handlePartialRefund(order);
        }
    }

    /**
     * 处理下部分退款完成，订单关闭的时候未结算变成已结算的金额处理，退款超时定时任务。
     * @param order 订单信息
     */
    private void handlePartialRefund(Order order) {
        // 1.获取到部分退款并且订单关闭后，需要结算给商家、平台的钱
        // 获取所有正在进行中的退款订单
        List<OrderRefund> orderRefunds = getProcessingOrderRefundByOrderId(order.getOrderId());
        double alreadyRefundAmount = 0.0;
        double changePlatformCommission = 0.0;
        double platformAllowanceAmount = 0.0;
        double distributionAmount = 0.0;
        for (OrderRefund orderRefund : orderRefunds) {
            if (Objects.equals(RefundType.ALL.value(), orderRefund.getRefundType())) {
                return;
            }
            alreadyRefundAmount = Arith.add(alreadyRefundAmount, orderRefund.getRefundAmount());
            changePlatformCommission = Arith.add(changePlatformCommission, orderRefund.getPlatformRefundCommission());
            platformAllowanceAmount = Arith.add(platformAllowanceAmount, orderRefund.getPlatformRefundAmount());
            distributionAmount = Arith.add(distributionAmount, orderRefund.getDistributionTotalAmount());
        }
        double partialRefundAmount = Arith.sub(order.getActualTotal(), alreadyRefundAmount);
        if (partialRefundAmount <= 0) {
            return;
        }
        OrderChangeShopWalletAmountBO orderChangeShopWalletAmountBO = new OrderChangeShopWalletAmountBO();
        orderChangeShopWalletAmountBO.setOrderStatus(order.getStatus());
        orderChangeShopWalletAmountBO.setActualTotal(order.getActualTotal());
        orderChangeShopWalletAmountBO.setRefundAmount(alreadyRefundAmount);
        orderChangeShopWalletAmountBO.setPlatformAllowanceAmount(Arith.sub(order.getPlatformAmount(), platformAllowanceAmount));
        orderChangeShopWalletAmountBO.setOrderNumber(order.getOrderNumber());
        orderChangeShopWalletAmountBO.setShopId(order.getShopId());
        orderChangeShopWalletAmountBO.setPlatformCommission(order.getPlatformCommission());
        orderChangeShopWalletAmountBO.setChangePlatformCommission(changePlatformCommission);
        orderChangeShopWalletAmountBO.setDistributionAmount(Arith.sub(order.getDistributionAmount(), distributionAmount));
        // 2.发送消息给商家，将需要结算的钱进行结算
        // 减少商家待结算金额
        applicationContext.publishEvent(new RefundSuccessSettlementEvent(order, orderChangeShopWalletAmountBO));

        // 订单结算状态改为已结算
        Order newOrder = new Order();
        newOrder.setOrderId(order.getOrderId());
        newOrder.setIsSettled(1);
        orderService.updateById(newOrder);
    }

    /**
     * 同意退款操作（生成结算记录）
     */
    private void agreeRefund(OrderRefundDto orderRefundDto) {
        Date nowDate = new Date();
        // 查询支付记录
        OrderSettlement orderSettlement = orderSettlementService.getById(orderRefundDto.getSettlementId());
        if (orderSettlement == null) {
            // 没有查询到支付记录，无法申请退款
            throw new YamiShopBindException("yami.not.refunds.requested");
        }
        if (refundOrderSettlementService.count(new LambdaQueryWrapper<RefundOrderSettlement>().eq(RefundOrderSettlement::getRefundSn, orderRefundDto.getRefundSn())) > 0) {
            // 订单正在进行退款结算，请勿重复操作
            throw new YamiShopBindException("yami.refund.progress");
        }

        // 生成退款结算记录
        RefundOrderSettlement refundOrderSettlement = new RefundOrderSettlement();
        refundOrderSettlement.setOrderNumber(orderRefundDto.getOrderNumber());
        refundOrderSettlement.setOrderPayNo(orderRefundDto.getOrderPayNo());
        refundOrderSettlement.setRefundSn(orderRefundDto.getRefundSn());
        refundOrderSettlement.setPayType(orderSettlement.getPayType());
        refundOrderSettlement.setRefundAmount(orderRefundDto.getRefundAmount());
        refundOrderSettlement.setOrderTotalAmount(orderRefundDto.getOrderAmount());
        refundOrderSettlement.setUserId(orderRefundDto.getUserId());
        refundOrderSettlement.setRefundStatus(1);
        refundOrderSettlement.setCreateTime(nowDate);
        refundOrderSettlement.setUpdateTime(nowDate);
        refundOrderSettlementService.save(refundOrderSettlement);

        // 更新退款单信息
        orderRefundDto.setDecisionTime(nowDate);
        orderRefundDto.setUpdateTime(nowDate);


    }

    /**
     * 提交退款请求（向微信发起退款请求）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitWxRefund(OrderRefundDto orderRefundDto) {
        // 判断是否已同意退款
        if (orderRefundDto.getDecisionTime() == null) {
            return;
        }
        OrderSettlement orderSettlement = orderSettlementService.getById(orderRefundDto.getSettlementId());
        RefundInfoDto refundInfo = new RefundInfoDto();
        refundInfo.setRefundSn(orderRefundDto.getRefundSn());
        refundInfo.setPayNo(orderSettlement.getPayNo());
        refundInfo.setRefundAmount(orderRefundDto.getRefundAmount());
        refundInfo.setRefundOrderNumbers(Collections.singletonList(orderSettlement.getOrderNumber()));
        refundInfoService.doRefund(refundInfo);
        payInfoService.markerRefund(orderSettlement.getPayNo());
    }

    @Override
    public double sumRefundSuccessAmountByOrderId(Long orderId) {
        return orderRefundMapper.sumRefundSuccessAmountByOrderId(orderId);
    }

    @Override
    public List<OrderRefund> getProcessingOrderRefundByOrderId(Long orderId) {
        return orderRefundMapper.getProcessingOrderRefundByOrderId(orderId);
    }

    /**
     * 退款成功（更新退款结算记录、更新订单、还原库存）
     */
    private void refundSuccess(Order order, OrderRefundDto orderRefundDto) {
        if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
            order.setStatus(OrderStatus.CLOSE.value());
            order.setCancelTime(new Date());
            order.setUpdateTime(new Date());
            order.setCloseType(OrderCloseType.REFUND.value());
            order.setRefundStatus(RefundStatusEnum.SUCCEED.value());
        } else {
            // 已退款单
            List<OrderRefund> orderRefundList = orderRefundMapper.selectList(new LambdaQueryWrapper<OrderRefund>()
                    .eq(OrderRefund::getOrderId, orderRefundDto.getOrderId())
                    .eq(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.SUCCESS.value())
            );

            // 查看是否已经达到了所有的订单数量，如是则订单关闭
            int totalRefundNum = statisticsTotalRefundNum(orderRefundList, orderRefundDto);

            // 整个订单完成退款的时候 - 是否已经达到了所有的订单数量，如是则订单关闭
            if (totalRefundNum >= order.getProductNums()) {
                order.setStatus(OrderStatus.CLOSE.value());
                order.setCancelTime(new Date());
                order.setUpdateTime(new Date());
                order.setCloseType(OrderCloseType.REFUND.value());
                order.setRefundStatus(RefundStatusEnum.SUCCEED.value());
            } else {
                order.setRefundStatus(RefundStatusEnum.PARTIAL_SUCCESS.value());
            }

            // 退款成功后，订单没有关闭，且发货订单项 + 退款成功订单项 = 订单项总数量 ，订单状态改为待收货
            if (!Objects.equals(order.getStatus(), OrderStatus.CLOSE.value()) && Objects.equals(order.getStatus(), OrderStatus.PADYED.value())) {
                List<OrderItem> list = orderItemService.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, order.getOrderNumber()));
                Integer unRefundCount = 0;
                Integer refundCount = 0;
                for (OrderItem orderItem : list) {
                    if (Objects.equals(orderItem.getOrderItemId(), orderRefundDto.getOrderItemId()) || Objects.equals(orderItem.getGiveawayOrderItemId(), orderRefundDto.getOrderItemId())) {
                        refundCount++;
                        continue;
                    }
                    if (Objects.equals(orderItem.getStatus(), 0)) {
                        unRefundCount++;
                    }
                }
                if (orderRefundList.size() + unRefundCount + refundCount >= list.size()) {
                    order.setStatus(OrderStatus.CONSIGNMENT.value());
                    order.setDvyTime(new Date());
                }
            }
        }
        orderService.updateById(order);

        // 还原库存
        OrderRefundDto orderRefund = getOrderRefundByRefundSn(orderRefundDto.getRefundSn());
        List<OrderItem> orderItems = orderRefund.getOrderItems();
        List<OrderItem> giveawayList = new ArrayList<>();
        Set<Long> prodIds = recoveryStock(order, orderRefundDto, orderRefund, orderItems, giveawayList);
        // 发票状态更改
        Long orderInvoiceId = orderInvoiceService.getByorderNumber(order.getOrderNumber());
        if (Objects.nonNull(orderInvoiceId)) {
            OrderInvoice orderInvoice = orderInvoiceService.getById(orderInvoiceId);
            if (Objects.nonNull(orderInvoice)) {
                orderInvoice.setInvoiceState(OrderInvoiceState.FAIL.value());
                orderInvoiceService.updateById(orderInvoice);
            }
        }
        // 退款成功处理
        orderRefundSuccessHandle(order, orderRefundDto, orderItems, giveawayList, prodIds);
    }

    private int statisticsTotalRefundNum(List<OrderRefund> orderRefundList, OrderRefundDto orderRefundDto) {
        // 获取原本的退货数量，不被之前的处理影响
        OrderRefund orderRefundByRefundSn = orderRefundMapper.selectById(orderRefundDto.getRefundId());
        int totalRefundNum = orderRefundByRefundSn.getGoodsNum();
        orderRefundDto.setGoodsNum(totalRefundNum);
//        int totalRefundNum = orderRefundDto.getGoodsNum();
        Set<String> giveawayOrderItemIds = new HashSet<>();

        // 添加当前退款商品的退款赠品订单项id列表
        if (StrUtil.isNotBlank(orderRefundDto.getReturnGiveawayIds())) {
            CollUtil.addAll(giveawayOrderItemIds, orderRefundDto.getReturnGiveawayIds().trim().split(Constant.COMMA));
        }

        // 添加已成功退款商品的退款赠品订单项id列表
        if (CollUtil.isNotEmpty(orderRefundList)) {
            for (OrderRefund orderRefund : orderRefundList) {
                totalRefundNum += orderRefund.getGoodsNum();
                if (StrUtil.isBlank(orderRefund.getReturnGiveawayIds())) {
                    continue;
                }
                CollUtil.addAll(giveawayOrderItemIds, orderRefund.getReturnGiveawayIds().trim().split(Constant.COMMA));
            }
        }
        if (CollUtil.isEmpty(giveawayOrderItemIds)) {
            return totalRefundNum;
        }
        // 根据退款赠品的订单项id列表，获取订单项信息
        List<OrderItem> list = orderItemService.list(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderItemId, giveawayOrderItemIds));
        if (CollUtil.isEmpty(list)) {
            return totalRefundNum;
        }
        // 统计赠品的退款数量
        totalRefundNum += list.stream().mapToInt(OrderItem::getProdCount).sum();
        return totalRefundNum;
    }

    /**
     * 取消申请超时的订单，无论该超时订单处于任何状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelWhenTimeOut(List<OrderRefund> orderRefundList) {
        Date now = new Date();
        List<Order> orders = new ArrayList<>();
        for (OrderRefund orderRefund : orderRefundList) {
            orderRefund.setReturnMoneySts(ReturnMoneyStsType.FAIL.value());
            orderRefund.setSellerMsg("申请退款超时");
            orderRefund.setCancelTime(now);
            orderRefund.setUpdateTime(now);

            // 批量修改订单退款状态
            Order order = new Order();
            order.setOrderId(orderRefund.getOrderId());
            Integer orderRefundSuccessCount = orderRefundMapper.selectCount(new LambdaQueryWrapper<OrderRefund>()
                    .eq(OrderRefund::getOrderId, orderRefund.getOrderId())
                    .eq(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.SUCCESS.value()));
            // 对退款金额发放失败的订单进行处理
            shopWalletService.handleRefundError(orderRefund);
            // 如果有订单项退款成功，则订单状态为部分退款成功，否则为退款失败
            if (orderRefundSuccessCount > 0) {
                order.setRefundStatus(RefundStatusEnum.PARTIAL_SUCCESS.value());
            } else {
                order.setRefundStatus(RefundStatusEnum.DISAGREE.value());
            }
            orders.add(order);
        }
        updateBatchById(orderRefundList);
        orderService.updateBatchById(orders);
    }

    @Override
    public boolean checkRefundDate(Order order) {
        // 判断是否超过支持的退款天数
        if (Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value())) {
            long finallyTime = order.getFinallyTime().getTime();
            long currentTime = System.currentTimeMillis();
            int miniTime = Constant.MAX_FINALLY_REFUND_TIME * 24 * 60 * 60 * 1000;
            return currentTime - finallyTime <= miniTime;
        }
        return true;
    }

    @Override
    public double sumRefundSuccessPlatformAmountByOrderId(Long orderId) {
        return orderRefundMapper.sumRefundSuccessPlatformAmountByOrderId(orderId);
    }

    @Override
    public UserManagerParam getRefundDataByUserId(UserManagerParam param) {
        String userId = param.getUserId();
        // 售后金额，退款金额
        Double amount = orderRefundMapper.countRefundAmountByUserId(userId);
        param.setAfterSaleAmount(Objects.nonNull(amount) ? amount : 0.0);
        // 售后次数，退款次数
        param.setAfterSaleTimes(orderRefundMapper.countRefundNumByUserId(userId));
        return param;
    }

    @Override
    public void updateByRefundSn(OrderRefund orderRefund) {
        orderRefundMapper.updateByRefundSn(orderRefund);
    }

    @Override
    public Boolean getIsLastRefund(String refundSn, Long shopId) {
        OrderRefundDto orderRefundDto = orderRefundMapper.getOrderRefundByRefundSn(refundSn);
        if (Objects.isNull(orderRefundDto)) {
            //退款单不存在
            throw new YamiShopBindException("yami.order.refund.exist");
        }
        if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
            //整单退款
            return false;
        }
        if (Objects.equals(orderRefundDto.getApplyType(), RefundApplyType.RETURN_REFUND.value())) {
            //退货退款
            return false;
        }
        Order order = orderService.getOrderByOrderNumberAndShopId(orderRefundDto.getOrderNumber(), shopId, true);
        if (!Objects.equals(order.getStatus(), OrderStatus.PADYED.value())) {
            //非待发货
            return false;
        }
        //退款成功总数
        int refundCount = count(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getOrderId, orderRefundDto.getOrderId())
                .eq(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.SUCCESS.value()));
        //所有订单项总数
        int orderItemCount = orderItemService.count(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderNumber, order.getOrderNumber())
                .isNull(OrderItem::getGiveawayOrderItemId));
        return Objects.equals(refundCount, orderItemCount - 1);
    }

    @Override
    public List<OrderRefundDto> listRefundInfoByRefundSnList(List<String> refundSnList) {
        if (CollUtil.isEmpty(refundSnList)) {
            return new ArrayList<>();
        }
        List<OrderRefundDto> orderRefundList = orderRefundMapper.listOrderRefundByRefundSn(refundSnList);
        orderRefundList.forEach(orderRefundDto -> getRefundTypeByOrderItem(orderRefundDto, 1));
        return orderRefundList;
    }

    private void checkLastRefund(OrderRefundDto orderRefundDto) {
        if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
            return;
        }
        Order order = orderService.getOrderByOrderNumber(orderRefundDto.getOrderNumber());
        if (!Objects.equals(order.getStatus(), OrderStatus.PADYED.value())) {
            return;
        }
        //所有订单项总数
        int orderItemCount = orderItemService.count(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderNumber, order.getOrderNumber())
                .isNull(OrderItem::getGiveawayOrderItemId));
        //退款成功总数
        int refundCount = count(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getOrderId, orderRefundDto.getOrderId())
                .eq(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.SUCCESS.value()));
        if (Objects.equals(refundCount, orderItemCount - 1) && order.getFreightAmount() > 0.0) {
            //最后一单
            if (order.getPlatformFreeFreightAmount() == 0.0) {
                orderRefundDto.setRefundAmount(Arith.add(order.getFreightAmount(), orderRefundDto.getRefundAmount()));
            }
        }
    }

    private Set<Long> recoveryStock(Order order, OrderRefundDto orderRefundDto, OrderRefundDto orderRefund, List<OrderItem> orderItems, List<OrderItem> giveawayList) {
        // 放入赠品一并还原赠品库存
        for (OrderItem orderItem : orderItems) {
            if (CollectionUtils.isNotEmpty(orderItem.getGiveawayList())) {
                giveawayList.addAll(orderItem.getGiveawayList());
            }
        }
        if (CollectionUtils.isNotEmpty(giveawayList)) {
            orderItems.addAll(giveawayList);
        }
        Set<Long> prodIds = new HashSet<>();
        List<Long> deleteIds = null;
        if (!Objects.equals(order.getOrderType(), OrderType.SECKILL.value())) {
            List<Long> skuIds = orderItems.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
            // 已删除的sku列表
            List<Sku> skuDeleteList = skuService.list(new LambdaQueryWrapper<Sku>().in(Sku::getSkuId, skuIds).eq(Sku::getIsDelete, 1));
            deleteIds = skuDeleteList.stream().map(Sku::getSkuId).collect(Collectors.toList());
        }
        for (OrderItem orderItem : orderItems) {
            prodIds.add(orderItem.getProdId());
            if (Objects.equals(order.getOrderType(), OrderType.SECKILL.value())) {
                // 退货退款或待发货仅退款
                boolean canReturnStock = Objects.equals(orderRefundDto.getApplyType(), 2) || (Objects.equals(orderRefundDto.getApplyType(), 1) && orderItem.getStatus() != 0);
                if (canReturnStock) {
                    // 秒杀订单，归还待发货库存到秒杀表
                    applicationContext.publishEvent(new UpdateSeckillOrderSkuInfoEvent(order.getOrderNumber(),
                            orderItem.getSkuId(), orderRefundDto.getRefundType(), orderItem.getProdCount(), orderRefund.getGoodsNum()));
                }
            }
            // 其他订单，归还待发货库存到商品表
            else {
                // 未全部发货，且sku没有删除的商品恢复库存，此时不需要核销的也会在这里进行退库存
                if (orderItem.getStatus() != 0 && !deleteIds.contains(orderItem.getSkuId())) {
                    prodExtensionMapper.addInventory(orderItem.getProdId(), orderItem.getStatus() == -1 ? orderItem.getProdCount() : orderItem.getStatus());
                    skuStockMapper.updateSkuStocks(orderItem.getSkuId(), orderItem.getStatus() == -1 ? orderItem.getProdCount() : orderItem.getStatus());
                }
                // 虚拟商品有核销时的退库存判断,没有核销完成时退库存
                if(Objects.equals(order.getOrderMold(),1) && Objects.equals(order.getWriteOffStatus(),0)) {
                    prodExtensionMapper.addInventory(orderItem.getProdId(), orderItem.getProdCount());
                    skuStockMapper.updateSkuStocks(orderItem.getSkuId(), orderItem.getProdCount());
                }
                skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
            }
        }
        return prodIds;
    }

    private void orderRefundSuccessHandle(Order order, OrderRefundDto orderRefundDto, List<OrderItem> orderItems, List<OrderItem> giveawayList, Set<Long> prodIds) {
        orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.SUCCESS.value());
        for (OrderItem orderItem : orderItems) {
            orderItem.setReturnMoneySts(ReturnMoneyStsType.SUCCESS.value());
        }
        orderRefundDto.setRefundTime(new Date());
        this.updateById(orderRefundDto);
        // 退款时分销需要计算 orderItems
        order.setOrderItems(orderItems);
        if (!Objects.equals(order.getOrderType(), OrderType.SECKILL.value())) {
            if (CollectionUtils.isNotEmpty(giveawayList)) {
                orderRefundDto.getOrderItems().addAll(giveawayList);
            }
            // 生成入库明细
            stockBillLogService.generateStockLogOfRefundOrder(orderRefundDto, StockBillType.RETURN_STORAGE.value(), StockType.WAREHOUSING.value());
        }
        List<String> keys = new ArrayList<>();
        for (Long prodId : prodIds) {
            keys.add("product" + Constant.UNION + prodId + '-' + LanguageEnum.LANGUAGE_EN.getLang());
            keys.add("product" + Constant.UNION + prodId + '-' + LanguageEnum.LANGUAGE_ZH_CN.getLang());
        }
        RedisUtil.del(keys);
        // 更新es中的商品
        eventPublisher.publishEvent(new EsProductUpdateEvent(null, new ArrayList<>(prodIds), EsOperationType.UPDATE_BATCH));
    }
}
